package init

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"user-server/basic/global"
)

func init() {
	InitConf()
	InitNacos()
	InitMysql()
	InitRedis()
}

func InitConf() {
	viper.SetConfigFile("./dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println("配置文件读取失败")
		return
	}
	err = viper.Unmarshal(&global.Na)
	if err != nil {
		fmt.Println("配置文件解析失败")
		return
	}
	fmt.Println(&global.Na)
}

func InitNacos() {
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.Na.NacosConfig.NamespaceId, // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.Na.NacosConfig.IpAddr,
			ContextPath: "/nacos",
			Port:        uint64(global.Na.NacosConfig.Port),
			Scheme:      "http",
		},
	}
	// 创建动态配置客户端
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, _ := configClient.GetConfig(vo.ConfigParam{
		DataId: global.Na.NacosConfig.DataId,
		Group:  global.Na.NacosConfig.Group})
	err := json.Unmarshal([]byte(content), &global.Conf)
	if err != nil {
		panic(err)
	}
	fmt.Println(content)
	log.Println(content)
}

func InitMysql() {
	var err error
	var conf = global.Conf.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", conf.User, conf.Password, conf.Host, conf.Port, conf.Db)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败")
		return
	}
	fmt.Println("数据库连接成功")
}

func InitRedis() {
	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     global.Conf.Redis.Addr,
		Password: global.Conf.Redis.Password, // no password set
		DB:       global.Conf.Redis.Db,       // use default DB
	})
}
